import { useState, useEffect } from "react";
import { invoke } from "@tauri-apps/api/core";
import Button from './components/ui/Button';
import Card from './components/ui/Card';
import Input from './components/ui/Input';
import StatusIndicator from './components/ui/StatusIndicator';

interface ProxyNode {
  host: string;
  port: number;
  username?: string;
  password?: string;
  type: 'http' | 'socks5';
}

interface ProxyConfig {
  host: string;
  port: number;
  username?: string;
  password?: string;
  type: 'http' | 'socks5';
  // 配置管理功能
  name?: string;
  group?: string;
  description?: string;
  createdAt?: string;
  lastUsed?: string;
  // 高级功能
  chain?: ProxyNode[];
  load_balance_servers?: ProxyNode[];
  load_balance_strategy?: 'round_robin' | 'random' | 'least_connections';
}

interface SystemProxyConfig {
  enable: boolean;
  server: string;
  port: number;
  bypass: string[];
}

interface TrafficStats {
  bytes_sent: number;
  bytes_received: number;
  connections_total: number;
  connections_active: number;
  start_time: number;
  last_activity: number;
}

interface ServerHealth {
  host: string;
  port: number;
  is_healthy: boolean;
  last_check: number;
  failure_count: number;
  response_time: number;
}

function App() {
  const [isConnected, setIsConnected] = useState(false);
  const [connectionInfo, setConnectionInfo] = useState<{
    startTime?: Date;
    localPort?: number;
    upstreamProxy?: string;
  }>({});
  const [proxyConfig, setProxyConfig] = useState<ProxyConfig>({
    host: '127.0.0.1',
    port: 8080,
    type: 'http'
  });
  const [status, setStatus] = useState('未连接');
  const [statusType, setStatusType] = useState<'info' | 'success' | 'warning' | 'error'>('info');
  const [isLoading, setIsLoading] = useState(false);
  const [responseTime, setResponseTime] = useState<number>(0);
  const [systemProxyEnabled, setSystemProxyEnabled] = useState(false);

  // 连接时长相关状态
  const [connectionStartTime, setConnectionStartTime] = useState<Date | null>(null);
  const [connectionDuration, setConnectionDuration] = useState('');
  const [connectionStats, setConnectionStats] = useState({
    totalConnections: 0,
    currentConnections: 0,
    bytesTransferred: 0
  });
  const [systemProxyConfig, setSystemProxyConfig] = useState<SystemProxyConfig>({
    enable: false,
    server: '127.0.0.1',
    port: 8888,
    bypass: ['localhost', '127.*', '10.*', '172.16.*', '192.168.*', '<local>']
  });
  const [savedConfigs, setSavedConfigs] = useState<ProxyConfig[]>([]);
  const [showSavedConfigs, setShowSavedConfigs] = useState(false);
  const [validationErrors, setValidationErrors] = useState<{[key: string]: string}>({});
  const [showProxyChain, setShowProxyChain] = useState(false);
  const [proxyChain, setProxyChain] = useState<ProxyNode[]>([]);
  const [trafficStats, setTrafficStats] = useState<TrafficStats>({
    bytes_sent: 0,
    bytes_received: 0,
    connections_total: 0,
    connections_active: 0,
    start_time: 0,
    last_activity: 0,
  });
  const [showTrafficStats, setShowTrafficStats] = useState(false);
  const [showLoadBalance, setShowLoadBalance] = useState(false);
  const [loadBalanceServers, setLoadBalanceServers] = useState<ProxyNode[]>([]);
  const [loadBalanceStrategy, setLoadBalanceStrategy] = useState<'round_robin' | 'random' | 'least_connections'>('round_robin');
  const [serverHealths, setServerHealths] = useState<ServerHealth[]>([]);
  const [showPerformanceMonitor, setShowPerformanceMonitor] = useState(false);
  const [showQuickMenu, setShowQuickMenu] = useState(false);
  const [showSettings, setShowSettings] = useState(false);

  // 配置管理状态
  const [selectedConfigs, setSelectedConfigs] = useState<number[]>([]);
  const [configFilter, setConfigFilter] = useState('');
  const [selectedGroup, setSelectedGroup] = useState('all');
  const [showConfigEditor, setShowConfigEditor] = useState(false);
  const [editingConfig, setEditingConfig] = useState<ProxyConfig | null>(null);
  const [editingIndex, setEditingIndex] = useState<number>(-1);

  // 测试相关状态
  const [testResults, setTestResults] = useState<Map<number, {
    status: 'testing' | 'success' | 'failed';
    latency?: number;
    message?: string;
    timestamp?: Date;
  }>>(new Map());
  const [showBatchTest, setShowBatchTest] = useState(false);
  const [batchTestProgress, setBatchTestProgress] = useState({ current: 0, total: 0 });

  // 应用设置状态（合并到上面的 showSettings）
  const [appSettings, setAppSettings] = useState({
    autoStart: false,
    minimizeToTray: true,
    darkMode: false
  });

  // 通知系统状态
  const [notifications, setNotifications] = useState<Array<{
    id: string;
    type: 'success' | 'error' | 'warning' | 'info';
    title: string;
    message: string;
    duration?: number;
  }>>([]);

  // 确认对话框状态
  const [confirmDialog, setConfirmDialog] = useState<{
    show: boolean;
    title: string;
    message: string;
    onConfirm: () => void;
    onCancel?: () => void;
    confirmText?: string;
    cancelText?: string;
    type?: 'danger' | 'warning' | 'info';
  }>({
    show: false,
    title: '',
    message: '',
    onConfirm: () => {},
  });

  // 更新状态的辅助函数
  const updateStatus = (message: string, type: 'info' | 'success' | 'warning' | 'error' = 'info') => {
    setStatus(message);
    setStatusType(type);
  };



  // 显示通知
  const showNotification = (
    type: 'success' | 'error' | 'warning' | 'info',
    title: string,
    message: string,
    duration: number = 5000
  ) => {
    const id = Date.now().toString();
    const notification = { id, type, title, message, duration };

    setNotifications(prev => [...prev, notification]);

    // 自动移除通知
    if (duration > 0) {
      setTimeout(() => {
        setNotifications(prev => prev.filter(n => n.id !== id));
      }, duration);
    }
  };

  // 移除通知
  const removeNotification = (id: string) => {
    setNotifications(prev => prev.filter(n => n.id !== id));
  };

  // 显示确认对话框
  const showConfirmDialog = (
    title: string,
    message: string,
    onConfirm: () => void,
    options?: {
      onCancel?: () => void;
      confirmText?: string;
      cancelText?: string;
      type?: 'danger' | 'warning' | 'info';
    }
  ) => {
    setConfirmDialog({
      show: true,
      title,
      message,
      onConfirm,
      onCancel: options?.onCancel,
      confirmText: options?.confirmText || '确认',
      cancelText: options?.cancelText || '取消',
      type: options?.type || 'info',
    });
  };

  // 隐藏确认对话框
  const hideConfirmDialog = () => {
    setConfirmDialog(prev => ({ ...prev, show: false }));
  };

  // 错误处理辅助函数
  const handleError = (error: any, defaultMessage: string, showAsNotification: boolean = true) => {
    console.error(defaultMessage, error);
    let errorMessage = defaultMessage;
    let errorDetails = '';

    if (typeof error === 'string') {
      errorMessage = error;
    } else if (error?.message) {
      errorMessage = error.message;
    } else if (error?.toString) {
      errorMessage = error.toString();
    }

    // 提供更友好的错误信息
    const friendlyErrorMessages: { [key: string]: string } = {
      '连接代理服务器失败': '无法连接到代理服务器，请检查服务器地址和端口是否正确',
      '代理需要认证': '代理服务器需要用户名和密码，请检查认证信息',
      '连接超时': '连接超时，请检查网络连接或尝试其他代理服务器',
      '代理响应异常': '代理服务器响应异常，可能服务器不可用',
      '无法找到 Host 头': '请求格式错误，这通常是代理配置问题',
      '不支持的代理类型': '当前不支持此代理类型，请选择 HTTP 或 SOCKS5',
    };

    // 查找友好的错误信息
    for (const [key, friendlyMessage] of Object.entries(friendlyErrorMessages)) {
      if (errorMessage.includes(key)) {
        errorDetails = friendlyMessage;
        break;
      }
    }

    updateStatus(errorMessage, 'error');

    if (showAsNotification) {
      showNotification(
        'error',
        '操作失败',
        errorDetails || errorMessage,
        8000 // 错误通知显示更长时间
      );
    }
  };

  // 验证代理配置
  const validateProxyConfig = (config: ProxyConfig): {[key: string]: string} => {
    const errors: {[key: string]: string} = {};

    // 验证主机地址
    if (!config.host || config.host.trim() === '') {
      errors.host = '服务器地址不能为空';
    } else if (config.host.includes(' ')) {
      errors.host = '服务器地址不能包含空格';
    } else {
      // 简单的IP地址或域名验证
      const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/;
      const domainRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

      if (!ipRegex.test(config.host) && !domainRegex.test(config.host)) {
        errors.host = '请输入有效的IP地址或域名';
      } else if (ipRegex.test(config.host)) {
        // 验证IP地址范围
        const parts = config.host.split('.').map(Number);
        if (parts.some(part => part < 0 || part > 255)) {
          errors.host = 'IP地址格式不正确';
        }
      }
    }

    // 验证端口
    if (!config.port || isNaN(config.port)) {
      errors.port = '端口号不能为空';
    } else if (config.port < 1 || config.port > 65535) {
      errors.port = '端口号必须在1-65535之间';
    }

    // 验证用户名（如果提供）
    if (config.username && config.username.includes(' ')) {
      errors.username = '用户名不能包含空格';
    }

    // 验证密码（如果提供了用户名但没有密码）
    if (config.username && !config.password) {
      errors.password = '提供用户名时必须输入密码';
    }

    return errors;
  };

  // 更新配置并验证
  const updateProxyConfig = (updates: Partial<ProxyConfig>) => {
    const newConfig = { ...proxyConfig, ...updates };
    setProxyConfig(newConfig);

    // 实时验证
    const errors = validateProxyConfig(newConfig);
    setValidationErrors(errors);
  };

  // 格式化连接时间
  const formatConnectionTime = (startTime: Date): string => {
    const now = new Date();
    const diff = Math.floor((now.getTime() - startTime.getTime()) / 1000);

    if (diff < 60) {
      return `${diff}秒`;
    } else if (diff < 3600) {
      const minutes = Math.floor(diff / 60);
      const seconds = diff % 60;
      return `${minutes}分${seconds}秒`;
    } else {
      const hours = Math.floor(diff / 3600);
      const minutes = Math.floor((diff % 3600) / 60);
      return `${hours}小时${minutes}分`;
    }
  };

  // 代理链管理函数
  const addProxyToChain = () => {
    const newNode: ProxyNode = {
      host: '127.0.0.1',
      port: 8080,
      type: 'http'
    };
    setProxyChain([...proxyChain, newNode]);
  };

  const removeProxyFromChain = (index: number) => {
    setProxyChain(proxyChain.filter((_, i) => i !== index));
  };

  const updateProxyInChain = (index: number, updates: Partial<ProxyNode>) => {
    const newChain = [...proxyChain];
    newChain[index] = { ...newChain[index], ...updates };
    setProxyChain(newChain);
  };

  const applyProxyChain = () => {
    if (proxyChain.length > 0) {
      const configWithChain = { ...proxyConfig, chain: proxyChain };
      setProxyConfig(configWithChain);
      updateStatus('代理链已应用', 'success');
    }
  };

  // 流量统计管理函数
  const loadTrafficStats = async () => {
    try {
      const stats = await invoke<TrafficStats>('get_traffic_stats');
      setTrafficStats(stats);
    } catch (error) {
      handleError(error, '获取流量统计失败');
    }
  };

  const resetTrafficStats = async () => {
    try {
      await invoke('reset_traffic_stats');
      await loadTrafficStats();
      updateStatus('流量统计已重置', 'success');
    } catch (error) {
      handleError(error, '重置流量统计失败');
    }
  };

  // 格式化字节数
  const formatBytes = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 格式化运行时间
  const formatUptime = (startTime: number): string => {
    if (startTime === 0) return '0秒';
    const now = Math.floor(Date.now() / 1000);
    const diff = now - startTime;

    if (diff < 60) {
      return `${diff}秒`;
    } else if (diff < 3600) {
      const minutes = Math.floor(diff / 60);
      const seconds = diff % 60;
      return `${minutes}分${seconds}秒`;
    } else {
      const hours = Math.floor(diff / 3600);
      const minutes = Math.floor((diff % 3600) / 60);
      return `${hours}小时${minutes}分`;
    }
  };

  // 负载均衡管理函数
  const addLoadBalanceServer = () => {
    const newServer: ProxyNode = {
      host: '127.0.0.1',
      port: 8080,
      type: 'http'
    };
    setLoadBalanceServers([...loadBalanceServers, newServer]);
  };

  const removeLoadBalanceServer = (index: number) => {
    setLoadBalanceServers(loadBalanceServers.filter((_, i) => i !== index));
  };

  const updateLoadBalanceServer = (index: number, updates: Partial<ProxyNode>) => {
    const newServers = [...loadBalanceServers];
    newServers[index] = { ...newServers[index], ...updates };
    setLoadBalanceServers(newServers);
  };

  const applyLoadBalance = () => {
    if (loadBalanceServers.length > 0) {
      const configWithLoadBalance = {
        ...proxyConfig,
        load_balance_servers: loadBalanceServers,
        load_balance_strategy: loadBalanceStrategy
      };
      setProxyConfig(configWithLoadBalance);
      updateStatus('负载均衡已应用', 'success');
    }
  };

  // 性能监控管理函数
  const checkServersHealth = async () => {
    try {
      if (loadBalanceServers.length > 0) {
        const healthResults = await invoke<ServerHealth[]>('check_servers_health', {
          servers: loadBalanceServers
        });
        setServerHealths(healthResults);
      }
    } catch (error) {
      handleError(error, '检查服务器健康状态失败');
    }
  };

  // 计算平均响应时间
  const getAverageResponseTime = (): number => {
    if (serverHealths.length === 0) return 0;
    const total = serverHealths.reduce((sum, health) => sum + health.response_time, 0);
    return Math.round(total / serverHealths.length);
  };

  // 获取健康服务器数量
  const getHealthyServerCount = (): number => {
    return serverHealths.filter(health => health.is_healthy).length;
  };

  // 加载保存的配置
  const loadSavedConfigs = async () => {
    try {
      const configs = await invoke<ProxyConfig[]>('load_proxy_configs');
      setSavedConfigs(configs);
    } catch (error) {
      handleError(error, '加载配置失败');
    }
  };

  // 保存当前配置
  const saveCurrentConfig = async () => {
    try {
      setIsLoading(true);
      await invoke('save_proxy_config', { config: proxyConfig });
      updateStatus('配置已保存', 'success');
      showNotification('success', '保存成功', '代理配置已成功保存');
      await loadSavedConfigs(); // 重新加载配置列表
    } catch (error) {
      handleError(error, '保存配置失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 删除配置
  const deleteConfig = async (index: number) => {
    const config = savedConfigs[index];
    if (!config) return;

    showConfirmDialog(
      '删除配置',
      `确定要删除配置 "${config.type.toUpperCase()} - ${config.host}:${config.port}" 吗？此操作无法撤销。`,
      async () => {
        try {
          setIsLoading(true);
          await invoke('delete_proxy_config', { index });
          updateStatus('配置已删除', 'success');
          showNotification('success', '删除成功', '代理配置已成功删除');
          await loadSavedConfigs(); // 重新加载配置列表
        } catch (error) {
          handleError(error, '删除配置失败');
        } finally {
          setIsLoading(false);
        }
        hideConfirmDialog();
      },
      {
        onCancel: hideConfirmDialog,
        confirmText: '删除',
        type: 'danger'
      }
    );
  };

  // 加载配置
  const loadConfig = (config: ProxyConfig) => {
    setProxyConfig(config);
    updateStatus('配置已加载', 'success');
    setShowSavedConfigs(false);
  };

  // 获取配置分组
  const getConfigGroups = () => {
    const groups = new Set<string>();
    savedConfigs.forEach(config => {
      if (config.group) {
        groups.add(config.group);
      }
    });
    return Array.from(groups).sort();
  };

  // 过滤配置
  const getFilteredConfigs = () => {
    return savedConfigs.filter(config => {
      const matchesFilter = !configFilter ||
        config.name?.toLowerCase().includes(configFilter.toLowerCase()) ||
        config.host.toLowerCase().includes(configFilter.toLowerCase()) ||
        config.description?.toLowerCase().includes(configFilter.toLowerCase());

      const matchesGroup = selectedGroup === 'all' ||
        (selectedGroup === 'ungrouped' && !config.group) ||
        config.group === selectedGroup;

      return matchesFilter && matchesGroup;
    });
  };

  // 编辑配置
  const editConfig = (config: ProxyConfig, index: number) => {
    setEditingConfig({ ...config });
    setEditingIndex(index);
    setShowConfigEditor(true);
  };

  // 保存编辑的配置
  const saveEditedConfig = async (updatedConfig: ProxyConfig) => {
    try {
      setIsLoading(true);

      // 更新配置数组
      const updatedConfigs = [...savedConfigs];
      updatedConfigs[editingIndex] = {
        ...updatedConfig,
        lastUsed: new Date().toISOString()
      };

      // 这里需要后端支持更新单个配置的功能
      // 暂时使用删除再添加的方式
      await invoke('delete_proxy_config', { index: editingIndex });
      await invoke('save_proxy_config', { config: updatedConfig });

      showNotification('success', '配置已更新', '代理配置已成功更新');
      await loadSavedConfigs();
      setShowConfigEditor(false);
      setEditingConfig(null);
      setEditingIndex(-1);
    } catch (error) {
      handleError(error, '更新配置失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 批量删除配置
  const deleteSelectedConfigs = async () => {
    if (selectedConfigs.length === 0) return;

    showConfirmDialog(
      '批量删除配置',
      `确定要删除选中的 ${selectedConfigs.length} 个配置吗？此操作无法撤销。`,
      async () => {
        try {
          setIsLoading(true);

          // 从后往前删除，避免索引变化问题
          const sortedIndices = selectedConfigs.sort((a, b) => b - a);
          for (const index of sortedIndices) {
            await invoke('delete_proxy_config', { index });
          }

          showNotification('success', '批量删除成功', `已删除 ${selectedConfigs.length} 个配置`);
          setSelectedConfigs([]);
          await loadSavedConfigs();
        } catch (error) {
          handleError(error, '批量删除失败');
        } finally {
          setIsLoading(false);
        }
        hideConfirmDialog();
      },
      {
        onCancel: hideConfirmDialog,
        confirmText: '删除',
        type: 'danger'
      }
    );
  };

  // 加载最后使用的配置
  const loadLastUsedConfig = async () => {
    try {
      const lastConfig = await invoke<ProxyConfig | null>('get_last_used_proxy');
      if (lastConfig) {
        setProxyConfig(lastConfig);
        updateStatus('已加载上次使用的配置', 'info');
      }
    } catch (error) {
      handleError(error, '加载最后使用的配置失败');
    }
  };

  // 测试代理连接
  const testConnection = async () => {
    try {
      // 验证配置
      const errors = validateProxyConfig(proxyConfig);
      if (Object.keys(errors).length > 0) {
        setValidationErrors(errors);
        updateStatus('请修正配置错误后再试', 'error');
        return;
      }

      setIsLoading(true);
      updateStatus('正在测试连接...', 'info');
      const startTime = Date.now();

      // 清除验证错误（如果存在）
      if (typeof setValidationErrors !== 'undefined') {
        setValidationErrors({});
      }

      const result = await invoke<string>('test_proxy_connection', { config: proxyConfig });
      const latency = Date.now() - startTime;

      setResponseTime(latency);
      updateStatus('连接成功', 'success');
      showNotification('success', '测试成功', `连接成功 (延迟: ${latency}ms)`);
    } catch (error) {
      handleError(error, '测试连接失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 测试单个配置
  const testSingleConfig = async (config: ProxyConfig, index: number) => {
    setTestResults(prev => new Map(prev.set(index, { status: 'testing', timestamp: new Date() })));

    try {
      const startTime = Date.now();
      const result = await invoke<string>('test_proxy_connection', { config });
      const latency = Date.now() - startTime;

      setTestResults(prev => new Map(prev.set(index, {
        status: 'success',
        latency,
        message: result,
        timestamp: new Date()
      })));

      showNotification('success', '测试成功', `${config.name || config.host} - ${result} (${latency}ms)`);
    } catch (error: any) {
      setTestResults(prev => new Map(prev.set(index, {
        status: 'failed',
        message: error.toString(),
        timestamp: new Date()
      })));

      showNotification('error', '测试失败', `${config.name || config.host} - ${error.toString()}`);
    }
  };

  // 批量测试配置
  const batchTestConfigs = async () => {
    const filteredConfigs = getFilteredConfigs();
    if (filteredConfigs.length === 0) {
      showNotification('warning', '无配置可测试', '请先添加一些代理配置');
      return;
    }

    setShowBatchTest(true);
    setBatchTestProgress({ current: 0, total: filteredConfigs.length });

    // 清除之前的测试结果
    setTestResults(new Map());

    for (let i = 0; i < filteredConfigs.length; i++) {
      const config = filteredConfigs[i];
      const actualIndex = savedConfigs.findIndex(c => c === config);

      setBatchTestProgress({ current: i + 1, total: filteredConfigs.length });
      await testSingleConfig(config, actualIndex);

      // 添加延迟避免过于频繁的请求
      if (i < filteredConfigs.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 500));
      }
    }

    setShowBatchTest(false);
    showNotification('info', '批量测试完成', `已测试 ${filteredConfigs.length} 个配置`);
  };

  // 获取测试结果状态图标
  const getTestStatusIcon = (index: number) => {
    const result = testResults.get(index);
    if (!result) return null;

    switch (result.status) {
      case 'testing':
        return <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>;
      case 'success':
        return (
          <div className="flex items-center text-green-600" title={`延迟: ${result.latency}ms`}>
            <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
            </svg>
            <span className="ml-1 text-xs">{result.latency}ms</span>
          </div>
        );
      case 'failed':
        return (
          <div className="text-red-600" title={result.message}>
            <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
            </svg>
          </div>
        );
      default:
        return null;
    }
  };

  // 导出配置
  const exportConfigs = () => {
    const configsToExport = selectedConfigs.length > 0
      ? selectedConfigs.map(index => savedConfigs[index])
      : savedConfigs;

    const exportData = {
      version: '1.0',
      timestamp: new Date().toISOString(),
      configs: configsToExport.map(config => ({
        ...config,
        // 出于安全考虑，不导出密码
        password: undefined
      }))
    };

    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);

    const link = document.createElement('a');
    link.href = url;
    link.download = `proxy-configs-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    showNotification('success', '导出成功', `已导出 ${configsToExport.length} 个配置`);
  };

  // 导入配置
  const importConfigs = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const content = e.target?.result as string;
        const importData = JSON.parse(content);

        // 验证导入数据格式
        if (!importData.configs || !Array.isArray(importData.configs)) {
          throw new Error('无效的配置文件格式');
        }

        let importedCount = 0;
        let skippedCount = 0;

        for (const config of importData.configs) {
          // 验证必需字段
          if (!config.host || !config.port || !config.type) {
            skippedCount++;
            continue;
          }

          // 检查是否已存在相同配置
          const exists = savedConfigs.some(existing =>
            existing.host === config.host &&
            existing.port === config.port &&
            existing.type === config.type
          );

          if (exists) {
            skippedCount++;
            continue;
          }

          try {
            await invoke('save_proxy_config', {
              config: {
                ...config,
                createdAt: new Date().toISOString()
              }
            });
            importedCount++;
          } catch (error) {
            console.error('导入配置失败:', error);
            skippedCount++;
          }
        }

        await loadSavedConfigs();

        if (importedCount > 0) {
          showNotification('success', '导入成功',
            `成功导入 ${importedCount} 个配置${skippedCount > 0 ? `，跳过 ${skippedCount} 个` : ''}`);
        } else {
          showNotification('warning', '导入完成', '没有新配置被导入');
        }

      } catch (error: any) {
        showNotification('error', '导入失败', error.message || '配置文件格式错误');
      }
    };

    reader.readAsText(file);
    // 清空文件输入，允许重复选择同一文件
    event.target.value = '';
  };

  const handleConnect = async () => {
    try {
      // 验证配置
      const errors = validateProxyConfig(proxyConfig);
      if (Object.keys(errors).length > 0) {
        setValidationErrors(errors);
        updateStatus('请修正配置错误后再试', 'error');
        return;
      }

      setIsLoading(true);
      updateStatus('正在连接...', 'info');
      const startTime = Date.now();

      // 清除验证错误
      setValidationErrors({});

      // 保存当前配置作为最后使用的配置
      await invoke('save_proxy_config', { config: proxyConfig });

      // 启动代理服务器
      await invoke('start_proxy', { config: proxyConfig });
      const latency = Date.now() - startTime;

      setIsConnected(true);
      setConnectionStartTime(new Date());
      setResponseTime(latency);
      setConnectionStats(prev => ({ ...prev, totalConnections: prev.totalConnections + 1 }));

      // 设置连接信息（如果存在）
      if (typeof setConnectionInfo !== 'undefined') {
        setConnectionInfo({
          startTime: new Date(),
          localPort: 8888, // 本地监听端口
          upstreamProxy: `${proxyConfig.type.toUpperCase()}://${proxyConfig.host}:${proxyConfig.port}`
        });
      }
      updateStatus('已连接', 'success');
      showNotification('success', '连接成功', `代理服务器已启动 (${proxyConfig.host}:${proxyConfig.port})`);

      // 重新加载配置列表和流量统计
      await loadSavedConfigs();
      await loadTrafficStats();
    } catch (error) {
      handleError(error, '连接失败');
    } finally {
      setIsLoading(false);
    }
  };

  const handleDisconnect = async () => {
    showConfirmDialog(
      '断开连接',
      '确定要断开代理连接吗？',
      async () => {
        try {
          setIsLoading(true);
          updateStatus('正在断开连接...', 'info');
          await invoke('stop_proxy');
          setIsConnected(false);
          setConnectionStartTime(null);
          setConnectionDuration('');
          setResponseTime(0);

          // 清除连接信息（如果存在）
          if (typeof setConnectionInfo !== 'undefined') {
            setConnectionInfo({});
          }

          updateStatus('未连接', 'info');
          showNotification('info', '已断开连接', '代理服务器已停止');
        } catch (error) {
          handleError(error, '断开连接失败');
        } finally {
          setIsLoading(false);
        }
        hideConfirmDialog();
      },
      {
        onCancel: hideConfirmDialog,
        confirmText: '断开连接',
        type: 'warning'
      }
    );
  };

  const handleSystemProxyToggle = async () => {
    try {
      const newConfig = {
        ...systemProxyConfig,
        enable: !systemProxyConfig.enable
      };

      await invoke('set_system_proxy_settings', { config: newConfig });
      setSystemProxyConfig(newConfig);
      setSystemProxyEnabled(newConfig.enable);

      if (newConfig.enable) {
        setStatus('系统代理已启用');
      } else {
        setStatus('系统代理已禁用');
      }
    } catch (error) {
      console.error('设置系统代理失败:', error);
      setStatus('系统代理设置失败');
    }
  };

  const loadSystemProxySettings = async () => {
    try {
      const config = await invoke<SystemProxyConfig>('get_system_proxy_settings');
      setSystemProxyConfig(config);
      setSystemProxyEnabled(config.enable);
    } catch (error) {
      console.error('获取系统代理设置失败:', error);
    }
  };

  // 加载应用设置
  const loadAppSettings = async () => {
    try {
      const [autoStart, minimizeToTray] = await invoke<[boolean, boolean]>('get_app_settings');
      setAppSettings(prev => ({
        ...prev,
        autoStart,
        minimizeToTray
      }));
    } catch (error) {
      console.error('获取应用设置失败:', error);
    }
  };

  // 保存应用设置
  const saveAppSettings = async (newSettings: typeof appSettings) => {
    try {
      setIsLoading(true);
      await invoke('save_app_settings', {
        autoStart: newSettings.autoStart,
        minimizeToTray: newSettings.minimizeToTray
      });
      setAppSettings(newSettings);
      updateStatus('设置已保存', 'success');
      showNotification('success', '设置已保存', '应用设置已成功更新');
    } catch (error) {
      handleError(error, '保存设置失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 切换深色模式
  const toggleDarkMode = () => {
    const newDarkMode = !appSettings.darkMode;
    const newSettings = { ...appSettings, darkMode: newDarkMode };
    setAppSettings(newSettings);

    // 更新 HTML 类名
    if (newDarkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }

    // 保存到本地存储
    localStorage.setItem('darkMode', newDarkMode.toString());
  };

  // 连接时长计算
  useEffect(() => {
    let interval: number;

    if (isConnected && connectionStartTime) {
      interval = setInterval(() => {
        const now = new Date();
        const diff = now.getTime() - connectionStartTime.getTime();

        const hours = Math.floor(diff / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((diff % (1000 * 60)) / 1000);

        if (hours > 0) {
          setConnectionDuration(`${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`);
        } else {
          setConnectionDuration(`${minutes}:${seconds.toString().padStart(2, '0')}`);
        }
      }, 1000);
    } else {
      setConnectionDuration('');
    }

    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [isConnected, connectionStartTime]);

  // 组件加载时获取系统代理设置和加载配置
  useEffect(() => {
    loadSystemProxySettings();
    loadSavedConfigs();
    loadLastUsedConfig();
    loadAppSettings();

    // 初始化深色模式
    const savedDarkMode = localStorage.getItem('darkMode') === 'true';
    setAppSettings(prev => ({ ...prev, darkMode: savedDarkMode }));
    if (savedDarkMode) {
      document.documentElement.classList.add('dark');
    }
  }, []);

  // 定期更新流量统计和服务器健康状态
  useEffect(() => {
    let interval: number;

    if (isConnected) {
      // 每5秒更新一次流量统计
      interval = window.setInterval(() => {
        loadTrafficStats();
        if (serverHealths.length > 0) {
          checkServersHealth();
        }
      }, 5000);
    }

    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [isConnected, serverHealths.length]);

  // 点击外部关闭快速菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (showQuickMenu) {
        const target = event.target as Element;
        if (!target.closest('.relative')) {
          setShowQuickMenu(false);
        }
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showQuickMenu]);

  // 定时更新连接时间和流量统计
  useEffect(() => {
    let interval: number;
    if (isConnected && connectionInfo.startTime) {
      interval = setInterval(() => {
        // 强制重新渲染以更新连接时间
        setConnectionInfo(prev => ({ ...prev }));
        // 更新流量统计
        loadTrafficStats();
      }, 1000);
    }
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [isConnected, connectionInfo.startTime]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 dark:from-gray-900 dark:to-slate-900 transition-colors duration-300">
      <div className="container mx-auto px-4 py-6 max-w-7xl">
        {/* 头部 */}
        <Card className="flex items-center justify-between mb-8 p-6 relative" hover={false}>
          <div className="flex items-center space-x-6">
            <div className="w-14 h-14 bg-gradient-to-r from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center shadow-lg animate-float">
              <svg className="w-7 h-7 text-white" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="flex-1">
              <h1 className="text-4xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 dark:from-white dark:to-gray-300 bg-clip-text text-transparent">
                代理工具
              </h1>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-1 font-medium">现代化的代理管理工具</p>
            </div>
          </div>

          {/* 连接状态 - 右上角悬浮 */}
          <div className="absolute -top-2 -right-2">
            <div
              className="flex items-center space-x-2 px-3 py-2 bg-white/90 dark:bg-gray-800/90 rounded-full shadow-lg border border-gray-200/50 dark:border-gray-600/50 cursor-pointer backdrop-blur-sm"
              title={
                isLoading ? '正在连接...' :
                isConnected ? `已连接${responseTime > 0 ? ` (${responseTime}ms)` : ''}` :
                '未连接'
              }
            >
              <StatusIndicator
                status={
                  isLoading ? 'connecting' :
                  isConnected ? 'connected' :
                  'disconnected'
                }
                size="sm"
                showLabel={false}
              />
              {isLoading && (
                <div className="animate-spin rounded-full h-3 w-3 border-2 border-blue-600 border-t-transparent"></div>
              )}
              {isConnected && responseTime > 0 && (
                <span className="text-xs font-semibold text-green-600 dark:text-green-400">
                  {responseTime}ms
                </span>
              )}
            </div>
          </div>
          <div className="flex items-center space-x-3">
            {/* 快速菜单按钮 */}
            <div className="relative">
              <button
                onClick={() => setShowQuickMenu(!showQuickMenu)}
                className="p-2 rounded-lg bg-gray-100/80 dark:bg-gray-700/80 hover:bg-gray-200 dark:hover:bg-gray-600 transition-all duration-200 border border-gray-200/50 dark:border-gray-600/50"
                title="快速菜单"
              >
                <svg className="w-4 h-4 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
                </svg>
              </button>

              {/* 快速菜单下拉 */}
              {showQuickMenu && (
                <div className="absolute right-0 mt-3 w-56 bg-white/95 dark:bg-gray-800/95 backdrop-blur-md rounded-2xl shadow-2xl border border-gray-200/50 dark:border-gray-700/50 z-50 animate-slide-up">
                  <div className="py-2">
                    <button
                      onClick={() => {
                        toggleDarkMode();
                        setShowQuickMenu(false);
                      }}
                      className="flex items-center w-full px-4 py-3 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors duration-150 rounded-lg mx-2"
                    >
                      {appSettings.darkMode ? (
                        <svg className="w-4 h-4 mr-3" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z" clipRule="evenodd" />
                        </svg>
                      ) : (
                        <svg className="w-4 h-4 mr-3" fill="currentColor" viewBox="0 0 20 20">
                          <path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z" />
                        </svg>
                      )}
                      {appSettings.darkMode ? '浅色模式' : '深色模式'}
                    </button>
                    <button
                      onClick={() => {
                        setShowPerformanceMonitor(true);
                        setShowQuickMenu(false);
                      }}
                      className="flex items-center w-full px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                    >
                      <svg className="w-4 h-4 mr-3" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M2 11a1 1 0 011-1h2a1 1 0 011 1v5a1 1 0 01-1 1H3a1 1 0 01-1-1v-5zM8 7a1 1 0 011-1h2a1 1 0 011 1v9a1 1 0 01-1 1H9a1 1 0 01-1-1V7zM14 4a1 1 0 011-1h2a1 1 0 011 1v12a1 1 0 01-1 1h-2a1 1 0 01-1-1V4z" />
                      </svg>
                      性能监控
                    </button>
                    <button
                      onClick={() => {
                        setShowSettings(true);
                        setShowQuickMenu(false);
                      }}
                      className="flex items-center w-full px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                    >
                      <svg className="w-4 h-4 mr-3" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clipRule="evenodd" />
                      </svg>
                      应用设置
                    </button>
                    {isConnected ? (
                      <button
                        onClick={() => {
                          handleDisconnect();
                          setShowQuickMenu(false);
                        }}
                        className="flex items-center w-full px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700"
                      >
                        <svg className="w-4 h-4 mr-3" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                        </svg>
                        断开连接
                      </button>
                    ) : (
                      <button
                        onClick={() => {
                          handleConnect();
                          setShowQuickMenu(false);
                        }}
                        className="flex items-center w-full px-4 py-2 text-sm text-green-600 dark:text-green-400 hover:bg-gray-100 dark:hover:bg-gray-700"
                      >
                        <svg className="w-4 h-4 mr-3" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-8.293l-3-3a1 1 0 00-1.414 1.414L10.586 9H7a1 1 0 100 2h3.586l-1.293 1.293a1 1 0 101.414 1.414l3-3a1 1 0 000-1.414z" clipRule="evenodd" />
                        </svg>
                        连接代理
                      </button>
                    )}
                  </div>
                </div>
              )}
            </div>

            {/* 深色模式切换按钮 */}
            <button
              onClick={toggleDarkMode}
              className="p-2 rounded-lg bg-gray-100/80 dark:bg-gray-700/80 hover:bg-gray-200 dark:hover:bg-gray-600 transition-all duration-200 border border-gray-200/50 dark:border-gray-600/50"
              title={appSettings.darkMode ? '切换到浅色模式' : '切换到深色模式'}
            >
              {appSettings.darkMode ? (
                <svg className="w-5 h-5 text-gray-800 dark:text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z" clipRule="evenodd" />
                </svg>
              ) : (
                <svg className="w-5 h-5 text-gray-800 dark:text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z" />
                </svg>
              )}
            </button>

            {/* 性能监控按钮 */}
            <button
              onClick={() => setShowPerformanceMonitor(!showPerformanceMonitor)}
              className="p-2 rounded-lg bg-gray-100/80 dark:bg-gray-700/80 hover:bg-gray-200 dark:hover:bg-gray-600 transition-all duration-200 border border-gray-200/50 dark:border-gray-600/50"
              title="性能监控"
            >
              <svg className="w-4 h-4 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                <path d="M2 11a1 1 0 011-1h2a1 1 0 011 1v5a1 1 0 01-1 1H3a1 1 0 01-1-1v-5zM8 7a1 1 0 011-1h2a1 1 0 011 1v9a1 1 0 01-1 1H9a1 1 0 01-1-1V7zM14 4a1 1 0 011-1h2a1 1 0 011 1v12a1 1 0 01-1 1h-2a1 1 0 01-1-1V4z" />
              </svg>
            </button>

            {/* 设置按钮 */}
            <button
              onClick={() => setShowSettings(!showSettings)}
              className="p-2 rounded-lg bg-gray-100/80 dark:bg-gray-700/80 hover:bg-gray-200 dark:hover:bg-gray-600 transition-all duration-200 border border-gray-200/50 dark:border-gray-600/50"
              title="应用设置"
            >
              <svg className="w-4 h-4 text-gray-600 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clipRule="evenodd" />
              </svg>
            </button>
          </div>
        </Card>

        {/* 连接详情 - 仅在连接时显示 */}
        {isConnected && (
          <Card className="p-6 mb-8">
            <h3 className="text-lg font-semibold text-gray-800 dark:text-white mb-4 flex items-center">
              <div className="w-6 h-6 bg-gradient-to-r from-green-400 to-blue-500 rounded-lg mr-3 flex items-center justify-center">
                <svg className="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                </svg>
              </div>
              连接详情
            </h3>

          {/* 连接详细信息 */}
          {isConnected && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-4 border-t border-gray-200 dark:border-gray-600">
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                  {connectionDuration || (connectionStartTime ? formatConnectionTime(connectionStartTime) : '00:00')}
                </div>
                <div className="text-sm text-gray-500 dark:text-gray-400">连接时长</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600 dark:text-green-400">
                  {proxyConfig.host}:{proxyConfig.port}
                </div>
                <div className="text-sm text-gray-500 dark:text-gray-400">代理服务器</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-purple-600 dark:text-purple-400">
                  {proxyConfig.type.toUpperCase()}
                </div>
                <div className="text-sm text-gray-500 dark:text-gray-400">协议类型</div>
              </div>
            </div>
          )}

          {/* 连接统计信息 */}
          {connectionStats.totalConnections > 0 && (
            <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-600">
              <div className="flex justify-between text-sm text-gray-600 dark:text-gray-300">
                <span>总连接次数: {connectionStats.totalConnections}</span>
                <span>当前连接: {connectionStats.currentConnections}</span>
              </div>
            </div>
          )}

          {/* 流量统计 */}
          {isConnected && (trafficStats.bytes_sent > 0 || trafficStats.bytes_received > 0) && (
            <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-600">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-lg font-medium text-gray-800 dark:text-white">流量统计</h3>
                <div className="flex space-x-2">
                  <button
                    onClick={() => setShowTrafficStats(!showTrafficStats)}
                    className="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                  >
                    {showTrafficStats ? '隐藏' : '显示'}详情
                  </button>
                  <button
                    onClick={resetTrafficStats}
                    className="px-3 py-1 bg-gray-600 text-white rounded text-sm hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-500 transition-colors"
                  >
                    重置
                  </button>
                </div>
              </div>

              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="text-center">
                  <div className="text-sm text-gray-500 dark:text-gray-400">上传</div>
                  <div className="text-lg font-semibold text-green-600 dark:text-green-400">
                    {formatBytes(trafficStats.bytes_sent)}
                  </div>
                </div>
                <div className="text-center">
                  <div className="text-sm text-gray-500 dark:text-gray-400">下载</div>
                  <div className="text-lg font-semibold text-blue-600 dark:text-blue-400">
                    {formatBytes(trafficStats.bytes_received)}
                  </div>
                </div>
                <div className="text-center">
                  <div className="text-sm text-gray-500 dark:text-gray-400">总连接</div>
                  <div className="text-lg font-semibold text-gray-800 dark:text-white">
                    {trafficStats.connections_total}
                  </div>
                </div>
                <div className="text-center">
                  <div className="text-sm text-gray-500 dark:text-gray-400">活跃连接</div>
                  <div className="text-lg font-semibold text-orange-600 dark:text-orange-400">
                    {trafficStats.connections_active}
                  </div>
                </div>
              </div>

              {showTrafficStats && (
                <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-600">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-gray-500 dark:text-gray-400">运行时间: </span>
                      <span className="text-gray-800 dark:text-white">{formatUptime(trafficStats.start_time)}</span>
                    </div>
                    <div>
                      <span className="text-gray-500 dark:text-gray-400">最后活动: </span>
                      <span className="text-gray-800 dark:text-white">
                        {trafficStats.last_activity > 0 ? new Date(trafficStats.last_activity * 1000).toLocaleTimeString() : '无'}
                      </span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
        </Card>
        )}

        {/* 代理配置 */}
        <Card className="p-8 mb-8">
          <h2 className="text-2xl font-bold mb-6 text-gray-800 dark:text-white flex items-center">
            <div className="w-10 h-10 bg-gradient-to-r from-purple-500 to-pink-600 rounded-xl mr-4 flex items-center justify-center shadow-lg">
              <svg className="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clipRule="evenodd" />
              </svg>
            </div>
            代理配置
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                代理类型
              </label>
              <select
                value={proxyConfig.type}
                onChange={(e) => setProxyConfig({...proxyConfig, type: e.target.value as 'http' | 'socks5'})}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              >
                <option value="http">HTTP</option>
                <option value="socks5">SOCKS5</option>
              </select>
            </div>

            <Input
              label="服务器地址"
              type="text"
              value={proxyConfig.host}
              onChange={(e) => updateProxyConfig({ host: e.target.value })}
              placeholder="127.0.0.1"
              error={validationErrors.host}
              icon={
                <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clipRule="evenodd" />
                </svg>
              }
            />

            <Input
              label="端口"
              type="number"
              value={proxyConfig.port.toString()}
              onChange={(e) => updateProxyConfig({ port: parseInt(e.target.value) || 0 })}
              placeholder="8080"
              error={validationErrors.port}
              min="1"
              max="65535"
              icon={
                <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd" />
                </svg>
              }
            />

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                用户名（可选）
              </label>
              <input
                type="text"
                value={proxyConfig.username || ''}
                onChange={(e) => updateProxyConfig({ username: e.target.value })}
                className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 dark:bg-gray-700 dark:text-white ${
                  validationErrors.username
                    ? 'border-red-500 focus:ring-red-500 dark:border-red-500'
                    : 'border-gray-300 focus:ring-blue-500 dark:border-gray-600'
                }`}
                placeholder="用户名"
              />
              {validationErrors.username && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">{validationErrors.username}</p>
              )}
            </div>

            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                密码（可选）
              </label>
              <input
                type="password"
                value={proxyConfig.password || ''}
                onChange={(e) => updateProxyConfig({ password: e.target.value })}
                className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 dark:bg-gray-700 dark:text-white ${
                  validationErrors.password
                    ? 'border-red-500 focus:ring-red-500 dark:border-red-500'
                    : 'border-gray-300 focus:ring-blue-500 dark:border-gray-600'
                }`}
                placeholder="密码"
              />
              {validationErrors.password && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">{validationErrors.password}</p>
              )}
            </div>
          </div>

          {/* 配置管理按钮 */}
          <div className="flex justify-between items-center mt-4 pt-4 border-t border-gray-200 dark:border-gray-600">
            <div className="flex space-x-2">
              <Button
                onClick={testConnection}
                disabled={isLoading}
                loading={isLoading}
                variant="secondary"
                size="md"
                icon={
                  <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M6.267 3.455a3.066 3.066 0 001.745-.723 3.066 3.066 0 013.976 0 3.066 3.066 0 001.745.723 3.066 3.066 0 012.812 2.812c.051.643.304 1.254.723 1.745a3.066 3.066 0 010 3.976 3.066 3.066 0 00-.723 1.745 3.066 3.066 0 01-2.812 2.812 3.066 3.066 0 00-1.745.723 3.066 3.066 0 01-3.976 0 3.066 3.066 0 00-1.745-.723 3.066 3.066 0 01-2.812-2.812 3.066 3.066 0 00-.723-1.745 3.066 3.066 0 010-3.976 3.066 3.066 0 00.723-1.745 3.066 3.066 0 012.812-2.812zm7.44 5.252a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                  </svg>
                }
              >
                {isLoading ? '测试中...' : '测试连接'}
              </Button>
              <Button
                onClick={saveCurrentConfig}
                disabled={isLoading}
                loading={isLoading}
                variant="primary"
                size="md"
                icon={
                  <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M7.707 10.293a1 1 0 10-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 11.586V6h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V8a2 2 0 012-2h5v5.586l-1.293-1.293zM9 4a1 1 0 012 0v2H9V4z" />
                  </svg>
                }
              >
                {isLoading ? '保存中...' : '保存配置'}
              </Button>
              <button
                onClick={() => setShowSavedConfigs(!showSavedConfigs)}
                disabled={isLoading}
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {showSavedConfigs ? '隐藏' : '管理'}配置
              </button>
              <button
                onClick={() => setShowProxyChain(!showProxyChain)}
                disabled={isLoading}
                className="px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {showProxyChain ? '隐藏' : '代理'}链
              </button>
              <button
                onClick={() => setShowLoadBalance(!showLoadBalance)}
                disabled={isLoading}
                className="px-4 py-2 bg-orange-600 text-white rounded-md hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-orange-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {showLoadBalance ? '隐藏' : '负载'}均衡
              </button>
            </div>
            <span className="text-sm text-gray-500 dark:text-gray-400">
              已保存 {savedConfigs.length} 个配置
            </span>
          </div>

          {/* 保存的配置列表 */}
          {showSavedConfigs && (
            <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-600">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-medium text-gray-800 dark:text-white">保存的配置</h3>
                <div className="flex items-center space-x-2">
                  {selectedConfigs.length > 0 && (
                    <button
                      onClick={deleteSelectedConfigs}
                      disabled={isLoading}
                      className="px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      删除选中 ({selectedConfigs.length})
                    </button>
                  )}
                  <button
                    onClick={batchTestConfigs}
                    disabled={isLoading || showBatchTest}
                    className="px-3 py-1 bg-purple-600 text-white rounded text-sm hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {showBatchTest ? `测试中 ${batchTestProgress.current}/${batchTestProgress.total}` : '批量测试'}
                  </button>
                  <button
                    onClick={exportConfigs}
                    className="px-3 py-1 bg-indigo-600 text-white rounded text-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-colors"
                  >
                    导出配置
                  </button>
                  <label className="px-3 py-1 bg-orange-600 text-white rounded text-sm hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-orange-500 transition-colors cursor-pointer">
                    导入配置
                    <input
                      type="file"
                      accept=".json"
                      onChange={importConfigs}
                      className="hidden"
                    />
                  </label>
                  <button
                    onClick={() => setShowConfigEditor(true)}
                    className="px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 transition-colors"
                  >
                    新建配置
                  </button>
                </div>
              </div>

              {/* 搜索和过滤 */}
              <div className="mb-4 space-y-2">
                <div className="flex space-x-2">
                  <input
                    type="text"
                    placeholder="搜索配置..."
                    value={configFilter}
                    onChange={(e) => setConfigFilter(e.target.value)}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  />
                  <select
                    value={selectedGroup}
                    onChange={(e) => setSelectedGroup(e.target.value)}
                    className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  >
                    <option value="all">所有分组</option>
                    <option value="ungrouped">未分组</option>
                    {getConfigGroups().map(group => (
                      <option key={group} value={group}>{group}</option>
                    ))}
                  </select>
                </div>
              </div>

              {savedConfigs.length === 0 ? (
                <p className="text-gray-500 dark:text-gray-400 text-center py-4">暂无保存的配置</p>
              ) : (
                <div className="space-y-2">
                  {getFilteredConfigs().map((config, _originalIndex) => {
                    const actualIndex = savedConfigs.findIndex(c => c === config);
                    return (
                      <div key={actualIndex} className="flex items-center p-3 bg-gray-50 dark:bg-gray-700 rounded-md">
                        <input
                          type="checkbox"
                          checked={selectedConfigs.includes(actualIndex)}
                          onChange={(e) => {
                            if (e.target.checked) {
                              setSelectedConfigs(prev => [...prev, actualIndex]);
                            } else {
                              setSelectedConfigs(prev => prev.filter(i => i !== actualIndex));
                            }
                          }}
                          className="mr-3 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                        />
                        <div className="flex-1">
                          <div className="flex items-center space-x-2">
                            <div className="font-medium text-gray-800 dark:text-white">
                              {config.name || `${config.type.toUpperCase()} - ${config.host}:${config.port}`}
                            </div>
                            {config.group && (
                              <span className="px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 text-xs rounded-full">
                                {config.group}
                              </span>
                            )}
                            {getTestStatusIcon(actualIndex)}
                          </div>
                          <div className="text-sm text-gray-600 dark:text-gray-300">
                            {config.host}:{config.port} ({config.type.toUpperCase()})
                            {config.username && ` • 用户: ${config.username}`}
                          </div>
                          {config.description && (
                            <div className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                              {config.description}
                            </div>
                          )}
                          {config.lastUsed && (
                            <div className="text-xs text-gray-400 dark:text-gray-500 mt-1">
                              最后使用: {new Date(config.lastUsed).toLocaleString()}
                            </div>
                          )}
                        </div>
                        <div className="flex space-x-2">
                          <button
                            onClick={() => testSingleConfig(config, actualIndex)}
                            disabled={isLoading || testResults.get(actualIndex)?.status === 'testing'}
                            className="px-3 py-1 bg-purple-600 text-white rounded text-sm hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            测试
                          </button>
                          <button
                            onClick={() => editConfig(config, actualIndex)}
                            disabled={isLoading}
                            className="px-3 py-1 bg-yellow-600 text-white rounded text-sm hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            编辑
                          </button>
                          <button
                            onClick={() => loadConfig(config)}
                            disabled={isLoading}
                            className="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            加载
                          </button>
                          <button
                            onClick={() => deleteConfig(actualIndex)}
                            disabled={isLoading}
                            className="px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                          >
                            删除
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}

          {/* 代理链管理 */}
          {showProxyChain && (
            <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-600">
              <h3 className="text-lg font-medium text-gray-800 dark:text-white mb-3">代理链配置</h3>
              <p className="text-sm text-gray-600 dark:text-gray-300 mb-4">
                配置多级代理链，流量将按顺序通过每个代理节点，提供更强的隐私保护
              </p>

              {proxyChain.length === 0 ? (
                <div className="text-center py-8">
                  <p className="text-gray-500 dark:text-gray-400 mb-4">暂无代理链节点</p>
                  <button
                    onClick={addProxyToChain}
                    className="px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 transition-colors"
                  >
                    添加第一个节点
                  </button>
                </div>
              ) : (
                <div className="space-y-4">
                  {proxyChain.map((node, index) => (
                    <div key={index} className="p-4 bg-gray-50 dark:bg-gray-700 rounded-md">
                      <div className="flex items-center justify-between mb-3">
                        <h4 className="font-medium text-gray-800 dark:text-white">
                          节点 {index + 1}
                        </h4>
                        <button
                          onClick={() => removeProxyFromChain(index)}
                          className="px-2 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 transition-colors"
                        >
                          删除
                        </button>
                      </div>

                      <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            类型
                          </label>
                          <select
                            value={node.type}
                            onChange={(e) => updateProxyInChain(index, { type: e.target.value as 'http' | 'socks5' })}
                            className="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-purple-500 dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                          >
                            <option value="http">HTTP</option>
                            <option value="socks5">SOCKS5</option>
                          </select>
                        </div>

                        <div>
                          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            地址
                          </label>
                          <input
                            type="text"
                            value={node.host}
                            onChange={(e) => updateProxyInChain(index, { host: e.target.value })}
                            className="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-purple-500 dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                            placeholder="127.0.0.1"
                          />
                        </div>

                        <div>
                          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            端口
                          </label>
                          <input
                            type="number"
                            value={node.port}
                            onChange={(e) => updateProxyInChain(index, { port: parseInt(e.target.value) || 0 })}
                            className="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-purple-500 dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                            placeholder="8080"
                            min="1"
                            max="65535"
                          />
                        </div>

                        <div>
                          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            用户名
                          </label>
                          <input
                            type="text"
                            value={node.username || ''}
                            onChange={(e) => updateProxyInChain(index, { username: e.target.value })}
                            className="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-purple-500 dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                            placeholder="可选"
                          />
                        </div>
                      </div>

                      {node.username && (
                        <div className="mt-3">
                          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                            密码
                          </label>
                          <input
                            type="password"
                            value={node.password || ''}
                            onChange={(e) => updateProxyInChain(index, { password: e.target.value })}
                            className="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-purple-500 dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                            placeholder="密码"
                          />
                        </div>
                      )}
                    </div>
                  ))}

                  <div className="flex justify-between items-center">
                    <button
                      onClick={addProxyToChain}
                      className="px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 transition-colors"
                    >
                      添加节点
                    </button>
                    <button
                      onClick={applyProxyChain}
                      className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 transition-colors"
                    >
                      应用代理链
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* 负载均衡配置 */}
          {showLoadBalance && (
            <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-600">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-medium text-gray-800 dark:text-white">负载均衡配置</h3>
                <div className="flex items-center space-x-2">
                  <select
                    value={loadBalanceStrategy}
                    onChange={(e) => setLoadBalanceStrategy(e.target.value as 'round_robin' | 'random' | 'least_connections')}
                    className="px-3 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  >
                    <option value="round_robin">轮询</option>
                    <option value="random">随机</option>
                    <option value="least_connections">最少连接</option>
                  </select>
                </div>
              </div>

              {loadBalanceServers.length === 0 ? (
                <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                  <p>暂无负载均衡服务器</p>
                  <button
                    onClick={addLoadBalanceServer}
                    className="mt-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                  >
                    添加服务器
                  </button>
                </div>
              ) : (
                <div className="space-y-3">
                  {loadBalanceServers.map((server, index) => (
                    <div key={index} className="flex items-center space-x-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-md">
                      <div className="flex-1 grid grid-cols-1 md:grid-cols-3 gap-3">
                        <input
                          type="text"
                          value={server.host}
                          onChange={(e) => updateLoadBalanceServer(index, { host: e.target.value })}
                          placeholder="服务器地址"
                          className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                        />
                        <input
                          type="number"
                          value={server.port}
                          onChange={(e) => updateLoadBalanceServer(index, { port: parseInt(e.target.value) })}
                          placeholder="端口"
                          min="1"
                          max="65535"
                          className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                        />
                        <input
                          type="text"
                          value={server.username || ''}
                          onChange={(e) => updateLoadBalanceServer(index, { username: e.target.value })}
                          placeholder="用户名（可选）"
                          className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                        />
                      </div>
                      <button
                        onClick={() => removeLoadBalanceServer(index)}
                        className="px-3 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 transition-colors"
                      >
                        删除
                      </button>
                    </div>
                  ))}

                  <div className="flex justify-between">
                    <button
                      onClick={addLoadBalanceServer}
                      className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                    >
                      添加服务器
                    </button>
                    <button
                      onClick={applyLoadBalance}
                      className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 transition-colors"
                    >
                      应用负载均衡
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}
        </Card>

        {/* 系统代理设置 */}
        <div className="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-6">
          <h2 className="text-xl font-semibold mb-4 text-gray-800 dark:text-white">系统代理设置</h2>

          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="text-lg font-medium text-gray-800 dark:text-white">启用系统代理</h3>
              <p className="text-sm text-gray-600 dark:text-gray-300">
                自动配置系统网络代理设置，所有应用程序将通过代理访问网络
              </p>
            </div>
            <button
              onClick={handleSystemProxyToggle}
              disabled={isLoading}
              className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed ${
                systemProxyEnabled ? 'bg-blue-600' : 'bg-gray-200 dark:bg-gray-700'
              }`}
            >
              <span
                className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                  systemProxyEnabled ? 'translate-x-6' : 'translate-x-1'
                }`}
              />
            </button>
          </div>

          {systemProxyEnabled && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t border-gray-200 dark:border-gray-600">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  代理服务器
                </label>
                <input
                  type="text"
                  value={systemProxyConfig.server}
                  onChange={(e) => setSystemProxyConfig({...systemProxyConfig, server: e.target.value})}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  placeholder="127.0.0.1"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  端口
                </label>
                <input
                  type="number"
                  value={systemProxyConfig.port}
                  onChange={(e) => setSystemProxyConfig({...systemProxyConfig, port: parseInt(e.target.value)})}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  placeholder="8888"
                />
              </div>

              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  代理例外（每行一个）
                </label>
                <textarea
                  value={systemProxyConfig.bypass.join('\n')}
                  onChange={(e) => setSystemProxyConfig({
                    ...systemProxyConfig,
                    bypass: e.target.value.split('\n').filter(line => line.trim())
                  })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                  rows={4}
                  placeholder="localhost&#10;127.*&#10;10.*&#10;192.168.*"
                />
              </div>
            </div>
          )}
        </div>

        {/* 性能监控界面 */}
        {showPerformanceMonitor && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-4xl mx-4 max-h-[90vh] overflow-y-auto">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-semibold text-gray-800 dark:text-white">性能监控</h2>
                <button
                  onClick={() => setShowPerformanceMonitor(false)}
                  className="p-1 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                >
                  <svg className="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                  </svg>
                </button>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* 服务器健康状态 */}
                <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="text-lg font-medium text-gray-800 dark:text-white">服务器健康状态</h3>
                    <button
                      onClick={checkServersHealth}
                      className="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                    >
                      刷新
                    </button>
                  </div>

                  {serverHealths.length === 0 ? (
                    <p className="text-gray-500 dark:text-gray-400 text-center py-4">暂无服务器健康数据</p>
                  ) : (
                    <div className="space-y-3">
                      {serverHealths.map((health, index) => (
                        <div key={index} className="flex items-center justify-between p-3 bg-white dark:bg-gray-600 rounded-md">
                          <div className="flex items-center space-x-3">
                            <div className={`w-3 h-3 rounded-full ${health.is_healthy ? 'bg-green-500' : 'bg-red-500'}`}></div>
                            <div>
                              <div className="font-medium text-gray-800 dark:text-white">
                                {health.host}:{health.port}
                              </div>
                              <div className="text-sm text-gray-500 dark:text-gray-400">
                                响应时间: {health.response_time}ms
                              </div>
                            </div>
                          </div>
                          <div className="text-right">
                            <div className="text-sm text-gray-500 dark:text-gray-400">
                              失败次数: {health.failure_count}
                            </div>
                            <div className="text-xs text-gray-400 dark:text-gray-500">
                              {new Date(health.last_check * 1000).toLocaleTimeString()}
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {/* 性能统计 */}
                <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                  <h3 className="text-lg font-medium text-gray-800 dark:text-white mb-4">性能统计</h3>

                  <div className="space-y-4">
                    <div className="flex justify-between">
                      <span className="text-gray-600 dark:text-gray-300">健康服务器数量:</span>
                      <span className="font-medium text-gray-800 dark:text-white">{getHealthyServerCount()}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600 dark:text-gray-300">平均响应时间:</span>
                      <span className="font-medium text-gray-800 dark:text-white">{getAverageResponseTime()}ms</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-600 dark:text-gray-300">总服务器数量:</span>
                      <span className="font-medium text-gray-800 dark:text-white">{serverHealths.length}</span>
                    </div>
                  </div>
                </div>
              </div>

              <div className="mt-6 flex justify-end">
                <button
                  onClick={() => setShowPerformanceMonitor(false)}
                  className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                >
                  关闭
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 配置编辑器 */}
        {showConfigEditor && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-semibold text-gray-800 dark:text-white">
                  {editingConfig ? '编辑配置' : '新建配置'}
                </h2>
                <button
                  onClick={() => {
                    setShowConfigEditor(false);
                    setEditingConfig(null);
                    setEditingIndex(-1);
                  }}
                  className="p-1 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                >
                  <svg className="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                  </svg>
                </button>
              </div>

              <form onSubmit={(e) => {
                e.preventDefault();
                const formData = new FormData(e.currentTarget);
                const configData: ProxyConfig = {
                  name: formData.get('name') as string || undefined,
                  host: formData.get('host') as string,
                  port: parseInt(formData.get('port') as string),
                  type: formData.get('type') as 'http' | 'socks5',
                  username: formData.get('username') as string || undefined,
                  password: formData.get('password') as string || undefined,
                  group: formData.get('group') as string || undefined,
                  description: formData.get('description') as string || undefined,
                  createdAt: editingConfig?.createdAt || new Date().toISOString(),
                  lastUsed: editingConfig?.lastUsed
                };

                if (editingConfig) {
                  saveEditedConfig(configData);
                } else {
                  // 新建配置
                  setProxyConfig(configData);
                  saveCurrentConfig();
                  setShowConfigEditor(false);
                }
              }} className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="md:col-span-2">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      配置名称
                    </label>
                    <input
                      type="text"
                      name="name"
                      defaultValue={editingConfig?.name || ''}
                      placeholder="为配置起个名字..."
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      代理类型 *
                    </label>
                    <select
                      name="type"
                      defaultValue={editingConfig?.type || 'http'}
                      required
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    >
                      <option value="http">HTTP</option>
                      <option value="socks5">SOCKS5</option>
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      分组
                    </label>
                    <input
                      type="text"
                      name="group"
                      defaultValue={editingConfig?.group || ''}
                      placeholder="配置分组..."
                      list="groups"
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    />
                    <datalist id="groups">
                      {getConfigGroups().map(group => (
                        <option key={group} value={group} />
                      ))}
                    </datalist>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      服务器地址 *
                    </label>
                    <input
                      type="text"
                      name="host"
                      defaultValue={editingConfig?.host || ''}
                      required
                      placeholder="127.0.0.1"
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      端口 *
                    </label>
                    <input
                      type="number"
                      name="port"
                      defaultValue={editingConfig?.port || ''}
                      required
                      min="1"
                      max="65535"
                      placeholder="8080"
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      用户名
                    </label>
                    <input
                      type="text"
                      name="username"
                      defaultValue={editingConfig?.username || ''}
                      placeholder="用户名（可选）"
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      密码
                    </label>
                    <input
                      type="password"
                      name="password"
                      defaultValue={editingConfig?.password || ''}
                      placeholder="密码（可选）"
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    />
                  </div>

                  <div className="md:col-span-2">
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      描述
                    </label>
                    <textarea
                      name="description"
                      defaultValue={editingConfig?.description || ''}
                      placeholder="配置描述..."
                      rows={3}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                    />
                  </div>
                </div>

                <div className="flex justify-end space-x-3 pt-4">
                  <button
                    type="button"
                    onClick={() => {
                      setShowConfigEditor(false);
                      setEditingConfig(null);
                      setEditingIndex(-1);
                    }}
                    className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    disabled={isLoading}
                    className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isLoading ? '保存中...' : (editingConfig ? '更新配置' : '创建配置')}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* 应用设置界面 */}
        {showSettings && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-md mx-4">
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-semibold text-gray-800 dark:text-white">应用设置</h2>
                <button
                  onClick={() => setShowSettings(false)}
                  className="p-1 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
                >
                  <svg className="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                  </svg>
                </button>
              </div>

              <div className="space-y-6">
                {/* 自动启动设置 */}
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="text-lg font-medium text-gray-800 dark:text-white">开机自启动</h3>
                    <p className="text-sm text-gray-600 dark:text-gray-300">
                      系统启动时自动运行代理工具
                    </p>
                  </div>
                  <button
                    onClick={() => {
                      const newSettings = { ...appSettings, autoStart: !appSettings.autoStart };
                      saveAppSettings(newSettings);
                    }}
                    disabled={isLoading}
                    className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed ${
                      appSettings.autoStart ? 'bg-blue-600' : 'bg-gray-200 dark:bg-gray-700'
                    }`}
                  >
                    <span
                      className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                        appSettings.autoStart ? 'translate-x-6' : 'translate-x-1'
                      }`}
                    />
                  </button>
                </div>

                {/* 最小化到托盘设置 */}
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="text-lg font-medium text-gray-800 dark:text-white">最小化到托盘</h3>
                    <p className="text-sm text-gray-600 dark:text-gray-300">
                      关闭窗口时最小化到系统托盘而不是退出
                    </p>
                  </div>
                  <button
                    onClick={() => {
                      const newSettings = { ...appSettings, minimizeToTray: !appSettings.minimizeToTray };
                      saveAppSettings(newSettings);
                    }}
                    disabled={isLoading}
                    className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed ${
                      appSettings.minimizeToTray ? 'bg-blue-600' : 'bg-gray-200 dark:bg-gray-700'
                    }`}
                  >
                    <span
                      className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                        appSettings.minimizeToTray ? 'translate-x-6' : 'translate-x-1'
                      }`}
                    />
                  </button>
                </div>

                {/* 主题设置 */}
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="text-lg font-medium text-gray-800 dark:text-white">深色模式</h3>
                    <p className="text-sm text-gray-600 dark:text-gray-300">
                      使用深色主题界面
                    </p>
                  </div>
                  <button
                    onClick={toggleDarkMode}
                    className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ${
                      appSettings.darkMode ? 'bg-blue-600' : 'bg-gray-200 dark:bg-gray-700'
                    }`}
                  >
                    <span
                      className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                        appSettings.darkMode ? 'translate-x-6' : 'translate-x-1'
                      }`}
                    />
                  </button>
                </div>
              </div>

              <div className="mt-6 flex justify-end">
                <button
                  onClick={() => setShowSettings(false)}
                  className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                >
                  完成
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 控制按钮 */}
        <div className="flex justify-center space-x-4">
          {!isConnected ? (
            <Button
              onClick={handleConnect}
              disabled={isLoading}
              loading={isLoading}
              variant="primary"
              size="lg"
              icon={
                <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-8.293l-3-3a1 1 0 00-1.414 1.414L10.586 9H7a1 1 0 100 2h3.586l-1.293 1.293a1 1 0 101.414 1.414l3-3a1 1 0 000-1.414z" clipRule="evenodd" />
                </svg>
              }
            >
              {isLoading ? '连接中...' : '连接代理'}
            </Button>
          ) : (
            <Button
              onClick={handleDisconnect}
              disabled={isLoading}
              loading={isLoading}
              variant="danger"
              size="lg"
              icon={
                <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                </svg>
              }
            >
              {isLoading ? '断开中...' : '断开连接'}
            </Button>
          )}
        </div>

        {/* 通知系统 */}
        <div className="fixed top-4 right-4 z-50 space-y-2">
          {notifications.map((notification) => (
            <div
              key={notification.id}
              className={`max-w-sm w-full bg-white dark:bg-gray-800 shadow-lg rounded-lg pointer-events-auto ring-1 ring-black ring-opacity-5 overflow-hidden transform transition-all duration-300 ease-in-out ${
                notification.type === 'success' ? 'border-l-4 border-green-500' :
                notification.type === 'error' ? 'border-l-4 border-red-500' :
                notification.type === 'warning' ? 'border-l-4 border-yellow-500' :
                'border-l-4 border-blue-500'
              }`}
            >
              <div className="p-4">
                <div className="flex items-start">
                  <div className="flex-shrink-0">
                    {notification.type === 'success' && (
                      <svg className="h-6 w-6 text-green-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    )}
                    {notification.type === 'error' && (
                      <svg className="h-6 w-6 text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    )}
                    {notification.type === 'warning' && (
                      <svg className="h-6 w-6 text-yellow-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                      </svg>
                    )}
                    {notification.type === 'info' && (
                      <svg className="h-6 w-6 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    )}
                  </div>
                  <div className="ml-3 w-0 flex-1 pt-0.5">
                    <p className="text-sm font-medium text-gray-900 dark:text-white">
                      {notification.title}
                    </p>
                    <p className="mt-1 text-sm text-gray-500 dark:text-gray-300">
                      {notification.message}
                    </p>
                  </div>
                  <div className="ml-4 flex-shrink-0 flex">
                    <button
                      className="bg-white dark:bg-gray-800 rounded-md inline-flex text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                      onClick={() => removeNotification(notification.id)}
                    >
                      <span className="sr-only">关闭</span>
                      <svg className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                        <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                      </svg>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* 确认对话框 */}
        {confirmDialog.show && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-md mx-4">
              <div className="flex items-center mb-4">
                {confirmDialog.type === 'danger' && (
                  <div className="flex-shrink-0">
                    <svg className="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                    </svg>
                  </div>
                )}
                {confirmDialog.type === 'warning' && (
                  <div className="flex-shrink-0">
                    <svg className="h-6 w-6 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                    </svg>
                  </div>
                )}
                <div className="ml-3">
                  <h3 className="text-lg font-medium text-gray-900 dark:text-white">
                    {confirmDialog.title}
                  </h3>
                </div>
              </div>

              <div className="mb-6">
                <p className="text-sm text-gray-500 dark:text-gray-300">
                  {confirmDialog.message}
                </p>
              </div>

              <div className="flex justify-end space-x-3">
                <button
                  onClick={confirmDialog.onCancel || hideConfirmDialog}
                  className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  {confirmDialog.cancelText}
                </button>
                <button
                  onClick={confirmDialog.onConfirm}
                  className={`px-4 py-2 text-sm font-medium text-white rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 ${
                    confirmDialog.type === 'danger'
                      ? 'bg-red-600 hover:bg-red-700 focus:ring-red-500'
                      : confirmDialog.type === 'warning'
                      ? 'bg-yellow-600 hover:bg-yellow-700 focus:ring-yellow-500'
                      : 'bg-blue-600 hover:bg-blue-700 focus:ring-blue-500'
                  }`}
                >
                  {confirmDialog.confirmText}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default App;
